package org.kl.bpm.cmd;

import java.sql.Date;

import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.joda.time.DateTime;
import org.kl.bf.entity.basic.User;
import org.kl.bf.utils.ApplicationContextHelper;
import org.kl.bpm.entity.conf.BpmDelegateHistory;
import org.kl.bpm.service.conf.BpmDelegateHistoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 委托任务.
 */
public class DelegateTaskCmd implements Command<Void> {
	private static Logger logger = LoggerFactory.getLogger(DelegateTaskCmd.class);
	private String taskId;
	private String attorney;

	public DelegateTaskCmd(String taskId, String attorney) {
		this.taskId = taskId;
		this.attorney = attorney;
	}

	/**
	 * 委托任务.
	 * 
	 */
	public Void execute(CommandContext commandContext) {
		TaskEntity task = Context.getCommandContext().getTaskEntityManager().findTaskById(taskId);

		String assignee = task.getAssignee();

		if (task.getOwner() == null) {
			task.setOwner(assignee);
		}

		task.setAssignee(attorney);
		BpmDelegateHistoryService bpmDelegateHistoryService = ApplicationContextHelper.getBean(BpmDelegateHistoryService.class);
		BpmDelegateHistory bpmDelegateHistory = new BpmDelegateHistory();
		bpmDelegateHistory.setAssignee(new User(assignee));
		bpmDelegateHistory.setAttorney(new User(attorney));
		bpmDelegateHistory.setDelegateTime(new Date(new DateTime().getMillis()));
		bpmDelegateHistory.setProcessDefinitionId(task.getProcessDefinitionId());
		bpmDelegateHistory.setProcessInstanceId(task.getProcessInstanceId());
		bpmDelegateHistory.setTaskDefinitionKey(task.getTaskDefinitionKey());
		bpmDelegateHistory.setTaskId(task.getId());
		bpmDelegateHistory.setStatus(1);
		bpmDelegateHistoryService.saveBpmDelegateHistory(bpmDelegateHistory);
		logger.info("委托任务[taskId:" + task.getId() + "]：" + assignee + "-->" + attorney);
		return null;
	}
}
